package walletadminlogic

import (
	"context"
	"go.uber.org/zap"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"

	"navi-mumbai/app/rpc/model/pg/wallet"
	"navi-mumbai/app/rpc/wallet/internal/svc"
	"navi-mumbai/app/rpc/wallet/pb"
	"navi-mumbai/common/xerr"

	"github.com/zeromicro/go-zero/core/logx"
)

type QueryPayChannelListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryPayChannelListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryPayChannelListLogic {
	return &QueryPayChannelListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 管理后台获取支付通道列表
func (l *QueryPayChannelListLogic) QueryPayChannelList(in *pb.QueryPayChannelListReq) (*pb.QueryPayChannelListResp, error) {
	defer utils.RecoverPanic()

	var err error
	var list []*wallet.PayChannelConfig
	list, err = l.svcCtx.PayChannelConfigModel.Find(l.ctx, 0, in.PageNo, in.PageSize)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
	}
	var resp pb.QueryPayChannelListResp
	resp.List = make([]*pb.PayChannel, 0)

	if len(list) <= 0 {
		return &resp, nil
	}

	if in.PageNo <= 1 {
		resp.Total, err = l.svcCtx.PayChannelConfigModel.Count(l.ctx, 0)
		if err != nil {
			l.Logger.Errorf("err == ", zap.Error(err))
			return nil, xerr.NewGrpcErrCodeMsg(xerr.DbError, err.Error())
		}
	}

	for i := 0; i < len(list); i++ {
		vl := pb.PayChannel{
			PayChannelId:      list[i].PayChannelId,
			PayChannelName:    list[i].PayChannelName,
			Logo:              list[i].Logo,
			MinCurrencyAmount: list[i].MinCurrencyAmount,
			MaxCurrencyAmount: list[i].MaxCurrencyAmount,
			IsInput:           list[i].IsInput,
			State:             list[i].State,
			CreateTime:        list[i].CreateTime.Format(dbkey.DateTimeCNFormat),
			UpdateTime:        list[i].UpdateTime.Format(dbkey.DateTimeCNFormat),
		}
		resp.List = append(resp.List, &vl)
	}

	return &resp, nil
}
